<template>
  <div class="address-list">
    <van-address-list v-model="chosenAddressId"
                      :list="addressList"
                      default-tag-text="默认"
                      add-button-text="+添加地址"
                      @select="onSelect"
                      @add="onAdd"
                      @edit="onEdit"/>
  </div>
</template>

<script>
import {getAddressListAPI} from "@/api/address.js";
import {getUserLocal} from "../../utils/auth";

export default {
  data() {
    return {
      chosenAddressId: "",
      addressList: [],
    };
  },

  created() {
    this.chosenAddressId = this.$route.params.addressId || "";
    this.user = getUserLocal();
    const userId = this.user.id;
    this.getAddressList(userId);
  },

  methods: {
    //触发增加（此时addressEdit路由功能还没实现）
    onAdd() {
      this.$router.push({
        name: "addressEdit"
      });
    },
    //触发编辑（此时addressEdit路由功能还没实现）
    onEdit(item) {
      this.$router.push({
        name: "addressEdit",
        params: {id: item.id},
      });
    },
    //获取登录用户的收货地址

    getAddressList(userId) {
      getAddressListAPI(userId).then(result => {
        result.data.forEach((item) => {
          let id = item.id
          let name = item.receiver
          let tel = item.cellPhone

          let address =
              item.province + item.city + item.county + item.address;
          let isDefault = item.is_default === 1;
          this.addressList.push({
            id,
            name,
            tel,
            address,
            isDefault,
          });
          //默认选择
          if (item.is_default === 1) {
            this.active_id = item.id;
          }
        });
      }).catch(() => {
      });
    },

    //处理点击列表
    onSelect(item) {
      let addressId = item.id;
      //路由有addressId参数表明是要选择地址id的，把选择结果路由传参返回。
      if (this.$route.params.addressId) {
        this.$router.replace({
          name: "orderCreate",
          params: {
            addressId
          },
        });
      }
    },
  },
};
</script>
<style scoped lang="less">
@bgColor: #f8f8f8;
@mainColor: #ff0000;
.address-list {
  min-height: 100vh;
  background: @bgColor;

  ::v-deep .van-address-list {
    margin-top: 5px;

    .van-address-item .van-radio__icon--checked .van-icon {
      background: @mainColor;
      border-color: @mainColor;
    }

    .van-button--danger {
      background: @mainColor;
    }
  }
}

::v-deep .van-address-item__name {
  font-size: 21px;
}

::v-deep .van-address-item__address {
  font-size: 18px;
}

::v-deep .van-address-item__tag {
  font-size: 15px;
}

.van-button--normal {
  height: 60px;
  font-size: 18px;
}
</style>